package com.whq.knowverywell.update;

import java.net.MalformedURLException;
import java.net.URL;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import com.whq.knowverywell.R;
import com.whq.knowverywell.activity.AboutActivity;
import com.whq.knowverywell.task.update.ApkUpdateAsyncTask;
import com.whq.knowverywell.util.AppUtil;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.constant.ParamConstant;

/**
 * app升级的工具类
 * @author wanghuaiqiang
 *
 */
public class AppUpdateUtil {
	private static final String TAG = "AppUpdateUtil";
	
	/**
     * 检查是否需要发送App更新通知,如果需要发送,则发送
     * @param context
     * @param newAppVersionCode
     * @param newAppVersionName
     * @param newApkName
     * @param newApkIntro
     */
    public static void chkAppUpdateNotification(Context context, 
    		int newAppVersionCode,  String newAppVersionName, String newApkName, String newApkIntro) {
//    	long now = System.currentTimeMillis();
//		if ( ((now - getLastUpateNotifyTime(context)) > CfgConstant.UPDATE_NOTIFY_INTERVAL_MILLISECOND) 
//				) {
			sendAppUpdateNotification(context, newAppVersionName, newApkName, newApkIntro);
//			setLastUpateNotifyTime(context, now);
//		}
    }
    
    /**
     * 发送App更新通知
     * @param context
     */
    private static void sendAppUpdateNotification(Context context, String appVersionName, String apkName, String appIntro){
		NotificationManager mNotificationManager =  (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "APP更新通知";
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		CharSequence contentTitle = "APP更新通知";
		CharSequence contentText = "发现新版本: " + appVersionName + ", 请及时更新!";
		notification.ledARGB = R.color.red;
		notification.flags = Notification.FLAG_ONLY_ALERT_ONCE;
		Intent notificationIntent = new Intent(context, AboutActivity.class);
		Bundle bundle = new Bundle();
		bundle.putString(ParamConstant.BUNDLE_KEY_APP_VERSION_NAME, appVersionName);
		bundle.putString(ParamConstant.BUNDLE_KEY_APP_APK_NAME, apkName);
		bundle.putString(ParamConstant.BUNDLE_KEY_APP_INTRO, appIntro);
		notificationIntent.putExtras(bundle);
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
		mNotificationManager.notify(CfgConstant.UPDATE_NOTIFY_ID, notification);
    }
    
    /**
     * 更新APP
     * @param context
     * @param appVersionName
     * @param apkName
     * @param appIntro
     */
    public static void doNewVersionUpdate(final Context context, final String appVersionName, final String apkName, String appIntro) {  
        StringBuffer sb = new StringBuffer(); 
        sb.append("当前版本：" + AppUtil.getVersionName(context)  + ", ");
        sb.append("发现新版本: " + appVersionName + ", ");
        sb.append("更新内容: " + appIntro + ", ");  
        sb.append("是否更新?");  
        Dialog dialog = new AlertDialog.Builder(context)  
                .setTitle("软件更新")  
                .setMessage(sb.toString())  
                // 设置内容  
                .setPositiveButton("更新",// 设置确定按钮  
                        new DialogInterface.OnClickListener() {  
                            @Override  
                            public void onClick(DialogInterface dialog,  
                                    int which) {  
//                            	 new UpdateTask(context, apkName).execute();
                            	String urlLink = CfgConstant.SERVER_HOST + CfgConstant.SERVER_CONTEXT + "/apk/" + apkName;
                            	URL urlObj = null;
                            	try {
									urlObj = new URL(urlLink);
								} catch (MalformedURLException e) {
									LogUtil.e(TAG, "生成URL(" + urlLink + ")出错：", e);
								}
                            	new ApkUpdateAsyncTask(context, appVersionName).execute(urlObj);
                            }  
                        })  
                .setNegativeButton("暂不更新",  
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,  
                                    int whichButton) {  
                                  
                            }  
                        }).create();// 创建  
        // 显示对话框  
        dialog.show();  
    }  
    
//    /**
//     * 获取更新notify的时间戳
//     * @param context
//     * @return
//     */
//	private static long getLastUpateNotifyTime(Context context) {
//		TblConfHandler tblConfHandler = new TblConfHandler(context);
//		return tblConfHandler.getOneLongConf(TblConfHandler.KEY_LAST_UPDATE_NOTIFY_TIME, 0l);
//	}
//
//	private static void setLastUpateNotifyTime(Context context, long lastTime) {
//		TblConfHandler tblConfHandler = new TblConfHandler(context);
//		tblConfHandler.saveOneConf(TblConfHandler.KEY_LAST_UPDATE_NOTIFY_TIME, lastTime);
//	}
}
